package org.dollarnotifier.transfer;

import java.io.IOException;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.abhimanyu.dataaccess.GoogleDatastoreDollarRateDao;
import com.abhimanyu.dataaccess.IDao;
import com.abhimanyu.dataaccess.model.DollarRate;
import com.google.appengine.tools.remoteapi.RemoteApiInstaller;
import com.google.appengine.tools.remoteapi.RemoteApiOptions;

public class GoogleToMySQLDollarRate {
	ApplicationContext context = null;
	IDao<DollarRate> mySQLDollarRateDao = null;
	// IDao<User> mySQLUserDao = null;

	IDao<DollarRate> googleDollarRateDao = null;

	// IDao<User> googleUserDao = null;
	public GoogleToMySQLDollarRate() {
		context = new ClassPathXmlApplicationContext("dataAccessContext.xml");
		// googleUserDao = (IDao<User>) context.getBean("googlestoreUsersDao");
		googleDollarRateDao = (IDao<DollarRate>) context
				.getBean("googleDatastoreDollarRateDao");

		// mySQLUserDao = (IDao<User>) context.getBean("usersDao");
		/*mySQLDollarRateDao = (IDao<DollarRate>) context
				.getBean("dollarRateDao");*/

	}

	private void transfer() {

		System.out.println("Ready to fetch data");
		List<DollarRate> list = googleDollarRateDao.fetchAll();
		System.out.println("Fetched data : " + list);
		for (DollarRate rate : list) {
			System.out.println("Saving : " + rate);
			mySQLDollarRateDao.save(rate);
		}
		System.out.println("Transferred " + list.size() + " records");
	}

	public void update() {
		googleDollarRateDao.update(null);

	}

	public static void main(String[] args) {
		RemoteApiOptions options = new RemoteApiOptions().server(
				"abhimanyuk-dollarrate-notifier.appspot.com", 443).credentials(
				args[0], args[1]);
		RemoteApiInstaller installer = new RemoteApiInstaller();
		try {
			installer.install(options);
			new GoogleToMySQLDollarRate().update();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			installer.uninstall();
		}

	}
}
